package com.tl.demo;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;

public class XwpfTest {

	public static void main(String[] args) throws Exception {
		jointWord3();
	}
	
	public static void jointWord3() throws Exception{
		XWPFDocument docTemp = new XWPFDocument(POIXMLDocument.openPackage("d://7.docx"));
		Iterator<XWPFTable> it = docTemp.getTablesIterator();
		XWPFTable table = it.next();
		int rowCount = table.getNumberOfRows();
		XWPFTableRow row1 = null;
		XWPFTableRow row2 = null;
		for(int i=0;i<rowCount;i++){
			XWPFTableRow row = table.getRow(i);
			String text = row.getCell(0).getText();
			
			List<XWPFTableCell> cells = row.getTableCells();
			for(XWPFTableCell c :cells){
				if(c.getText().contains("${NAME}")){
					XWPFParagraph p = c.getParagraphs().get(0);
					p.removeRun(0);
					p.insertNewRun(0).setText("tl");
				}
			}
			
			if(text.contains("工作经历")){
				//记住要增加的行
				CTRow ctrow=(CTRow) row.getCtRow().copy();
				row1=new XWPFTableRow(ctrow,table);
			}
			
			if(text.contains("${TIME}")){
				//记住要增加的另外的一行
				CTRow ctrow=(CTRow) row.getCtRow().copy();
				row2=new XWPFTableRow(ctrow,table);
			}
		}
		
		XWPFTableRow row3 = row1;
		
		row3.getCell(0).setText("4444444444");
		
		
		table.addRow(row3);
		table.addRow(row2);
		table.addRow(row1);
		
		FileOutputStream out = new FileOutputStream("d://demo.doc");
		docTemp.write(out);
		
	}
	
	
	

	public static void jointWord2() throws Exception{
		
		XWPFDocument docTemp = new XWPFDocument(POIXMLDocument.openPackage("d://7.docx"));
		XWPFDocument doc = new XWPFDocument();
		XWPFTable next = docTemp.getTablesIterator().next();
		
		//复制table
		
		XWPFTable table=doc.createTable();
		//复制模板table的属性
		CTTblPr x1TablePr = table.getCTTbl().addNewTblPr();
		x1TablePr.setTblBorders(next.getCTTbl().getTblPr().getTblBorders());
		
		//复制表格
		int rowcount=next.getNumberOfRows();
		for(int t=0;t<rowcount;t++)
		{// 遍历行
			
			XWPFTableRow row = next.getRow(t);
			
			
			CTRow ctrow=(CTRow) row.getCtRow().copy();
			XWPFTableRow row2=new XWPFTableRow(ctrow,table);
			XWPFTableCell cell = row.getCell(0);
			System.out.println(cell.getText());
			table.addRow(row2);
//			if(row.getCell(0).getText().contains("电子")){
			
//			CTRow ctrow2=(CTRow)next.getRow(t).getCtRow().copy();
//			XWPFTableRow row3=new XWPFTableRow(ctrow2,table);
			
			
			
			XWPFTableRow row4 = table.createRow();
			XWPFTableCell cell1 = row4.createCell();
			cell1.setText("22222222222222222222");
			
//			row4.getCell(0).setText("111111");
//			row4.getCell(1).setText("2222");
			
//			XWPFTableRow row3=new XWPFTableRow(null,table);
//			table.addRow(row3);
//			}
		}
//		
//		Map<String, Object> params = new HashMap<String,Object>();
//		params.put("${NAME}", "tl");
		
//		int rowCount = table.getNumberOfRows();
//		for(int i=0;i<rowCount;i++){
//			XWPFTableRow row = table.getRow(i);
//			List<XWPFTableCell> cells = row.getTableCells();
//			boolean flag = false;
//			for(XWPFTableCell c:cells){
//				System.out.println(c.getText());
//				List<XWPFParagraph> paras = c.getParagraphs();
//                for (XWPFParagraph para : paras) {
//                   replaceInPara(para, params);
//                }
//				
//				if("${ADD}".equals(c.getText())){
//					flag = true;
//				}
//			}
//			if(flag == true){
//				CTRow ctrow=(CTRow) row.getCtRow().copy();
//				XWPFTableRow row2=new XWPFTableRow(ctrow,table);
//				System.out.println(row2.getCell(1).getText()+"=================================================");
////					List<XWPFTableCell> tableCells = row2.getTableCells();
////					for(XWPFTableCell c2:tableCells){
////						c2.removeParagraph(0);
////						c2.setText("555555555");
////					}
//				table.addRow(row2);
//			}
//			
//		}
		
		
//		XWPFTable tableTemp = docTemp.getTablesIterator().next();
//		int rowcount1=tableTemp.getNumberOfRows();
//		for(int t=0;t<rowcount1;t++)
//		{
//			XWPFTableRow row = tableTemp.getRow(t);
//			
//			CTRow ctrow=(CTRow)tableTemp.getRow(t).getCtRow().copy();
//			XWPFTableRow row1=new XWPFTableRow(ctrow,tableTemp);
//			tableTemp.addRow(row1);
//			
//			XWPFTableCell cell = row.getCell(0);
//			
//			if(cell.getText().contains("电子")){
////				CTRow ctrow1=(CTRow) row.getCtRow().copy();
////				XWPFTableRow row2=new XWPFTableRow(ctrow1,tableTemp);
//				tableTemp.addRow(row1);
//			}
//		}
		
		double random = Math.random()*100;
		FileOutputStream out = new FileOutputStream("d://"+random+".doc");
		docTemp.write(out);
	}
	
	
	 /**
	    * 替换段落里面的变量
	    * @param para 要替换的段落
	    * @param params 参数
	    */
   private static void replaceInPara(XWPFParagraph para, Map<String, Object> params) {
      List<XWPFRun> runs;
      Matcher matcher;
      if (matcher(para.getParagraphText()).find()) {
         runs = para.getRuns();
         for (int i=0; i<runs.size(); i++) {
            XWPFRun run = runs.get(i);
            String runText = run.toString();
            matcher = matcher(runText);
            if (matcher.find()) {
                while ((matcher = matcher(runText)).find()) {
                   runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))));
                }
                //直接调用XWPFRun的setText()方法设置文本时，在底层会重新创建一个XWPFRun，把文本附加在当前文本后面，
                //所以我们不能直接设值，需要先删除当前run,然后再自己手动插入一个新的run。
                para.removeRun(i);
                para.insertNewRun(i).setText(runText);
            }
         }
      }
   }

   
   /**
    * 正则匹配字符串
    * @param str
    * @return
    */
   private static Matcher matcher(String str) {
      Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
      Matcher matcher = pattern.matcher(str);
      boolean find = matcher.find();
      System.out.println(find);
      return matcher;
   }
	
   
   
	public static void jointWord() throws Exception{
		
		XWPFDocument docTemp = new XWPFDocument(POIXMLDocument.openPackage("d://template.docx"));
		XWPFDocument doc = new XWPFDocument();
		Iterator<XWPFTable> it = docTemp.getTablesIterator();
		XWPFTable tableTemp = it.next();
		
		XWPFTable table = doc.createTable();
		CTTblPr tablePr = table.getCTTbl().addNewTblPr();
		tablePr.setTblBorders(tableTemp.getCTTbl().getTblPr().getTblBorders());
		
		
		int rowcount=tableTemp.getNumberOfRows();
		for(int t=0;t<rowcount;t++)
		{// 遍历行
			CTRow ctrow=(CTRow)tableTemp.getRow(t).getCtRow().copy();
			XWPFTableRow row=new XWPFTableRow(ctrow,table);
			tableTemp.addRow(row);
		}
		
		FileOutputStream out = new FileOutputStream("d://temple2.doc");
		docTemp.write(out);
	}
	
	
	/**
	 * 基本的写操作
	 * 
	 * @throws Exception
	 */
	public static void testSimpleWrite() throws Exception {
		// 新建一个文档
		XWPFDocument doc = new XWPFDocument();
		// 创建一个段落
		XWPFParagraph para = doc.createParagraph();

		// 一个XWPFRun代表具有相同属性的一个区域。
		XWPFRun run = para.createRun();
		run.setBold(true); // 加粗
		run.setText("加粗的内容");
		run = para.createRun();
		run.setColor("FF0000");
		run.setText("红色的字。");
		OutputStream os = new FileOutputStream("D:\\simpleWrite.docx");
		// 把doc输出到输出流
		doc.write(os);
		close(os);
	}

	/***
	 * 写一个表格
	 * 
	 * @throws Exception
	 */
	public static void testWriteTable() throws Exception {
		XWPFDocument doc = new XWPFDocument();
		// 创建一个5行5列的表格
		XWPFTable table = doc.createTable(5, 5);
		// 这里增加的列原本初始化创建的那5行在通过getTableCells()方法获取时获取不到，但通过row新增的就可以。
		// table.addNewCol(); //给表格增加一列，变成6列
		table.createRow(); // 给表格新增一行，变成6行
		List<XWPFTableRow> rows = table.getRows();
		// 表格属性
		CTTblPr tablePr = table.getCTTbl().addNewTblPr();
		// 表格宽度
		CTTblWidth width = tablePr.addNewTblW();
		width.setW(BigInteger.valueOf(8000));
		XWPFTableRow row;
		List<XWPFTableCell> cells;
		XWPFTableCell cell;
		int rowSize = rows.size();
		int cellSize;
		for (int i = 0; i < rowSize; i++) {
			row = rows.get(i);
			// 新增单元格
			row.addNewTableCell();
			// 设置行的高度
			row.setHeight(500);
			// 行属性
			// CTTrPr rowPr = row.getCtRow().addNewTrPr();
			// 这种方式是可以获取到新增的cell的。
			// List<CTTc> list = row.getCtRow().getTcList();
			cells = row.getTableCells();
			cellSize = cells.size();
			for (int j = 0; j < cellSize; j++) {
				cell = cells.get(j);
				if ((i + j) % 2 == 0) {
					// 设置单元格的颜色
					cell.setColor("ff0000"); // 红色
				} else {
					cell.setColor("0000ff"); // 蓝色
				}
				// 单元格属性
				CTTcPr cellPr = cell.getCTTc().addNewTcPr();
				cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);
				if (j == 3) {
					// 设置宽度
					cellPr.addNewTcW().setW(BigInteger.valueOf(3000));
				}
				cell.setText(i + ", " + j);
			}
		}
		// 文件不存在时会自动创建
		OutputStream os = new FileOutputStream("D:\\table.docx");
		// 写入文件
		doc.write(os);
		close(os);
	}

	/**
	 * 关闭输出流
	 * 
	 * @param os
	 */
	private static void close(OutputStream os) {
		if (os != null) {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
